package org.android.contacts.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class PhotoUtil {

	public static String savePhoto(byte[] data, ContentResolver contentResolver) {
		if (data == null)
			return "";

		Bitmap photo = BitmapFactory.decodeByteArray(data, 0, data.length);

		String path = Environment.getExternalStorageDirectory().toString();
		File file = new File(path, getPhotoFileName());
		try {
			OutputStream fOut = new FileOutputStream(file);
			photo.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
			fOut.close();

			MediaStore.Images.Media.insertImage(contentResolver,
					file.getAbsolutePath(), file.getName(), file.getName());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		return file.getAbsolutePath();
	}

	public static byte[] loadPhoto(String pathName) {
		Bitmap bitmap = BitmapFactory.decodeFile(pathName);
		return toByteArray(bitmap);
	}
	
	public static byte[] toByteArray(Bitmap photo) {
		if (photo == null)
			return null;
 
		final int size = photo.getWidth() * photo.getHeight() * 4;
        final ByteArrayOutputStream out = new ByteArrayOutputStream(size);

        try {
            photo.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            Log.w("PhotoUtil", "Unable to serialize photo: " + e.toString());
            return null;
        }
	}

	private static String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".png";
	}
}
